package com.ffcc.fitness.trade.service.impl;

import com.ffcc.fitness.trade.mapper.TradeMapper;
import com.ffcc.fitness.trade.pojo.dto.TradeInsertParam;
import com.ffcc.fitness.trade.pojo.dto.TradeUpdateParam;
import com.ffcc.fitness.trade.pojo.entity.Trade;
import com.ffcc.fitness.trade.pojo.vo.TradeVO;
import com.ffcc.fitness.trade.service.TradeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class TradeServiceImpl implements TradeService {

    @Autowired
    private TradeMapper tradeMapper;    @Override
    public void insert(TradeInsertParam tradeInsertParam) {
        Trade trade = new Trade();
        BeanUtils.copyProperties(tradeInsertParam, trade);

        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        trade.setCreateTime(now);
        trade.setUpdateTime(now);

        // 设置初始状态为可用(AVAILABLE)
        trade.setStatus("AVAILABLE");        // 调试日志
        log.info("插入交易数据: equipmentType={}, conditionLevel={}, images={}", 
                trade.getEquipmentType(), trade.getConditionLevel(), trade.getImages());

        // 插入交易数据
        tradeMapper.insert(trade);
    }    @Override
    public List<TradeVO> select() {
        return tradeMapper.select();
    }

    @Override
    public TradeVO selectById(Long tradeId) {
        log.info("根据交易ID查询交易详情: tradeId={}", tradeId);
        return tradeMapper.selectById(tradeId);
    }

    @Override
    public List<TradeVO> selectByUserId(Long userId) {
        log.info("根据用户ID查询交易列表: userId={}", userId);
        return tradeMapper.selectByUserId(userId);
    }

    @Override
    public void update(TradeUpdateParam tradeUpdateParam) {
        log.info("更新交易信息: {}", tradeUpdateParam);
        
        Trade trade = new Trade();
        BeanUtils.copyProperties(tradeUpdateParam, trade);
        
        // 设置更新时间
        trade.setUpdateTime(LocalDateTime.now());
        
        // 更新交易数据
        tradeMapper.update(trade);
        
        log.info("交易信息更新成功: tradeId={}", tradeUpdateParam.getTradeId());
    }    @Override
    public void delete(Long tradeId, Long userId) {
        log.info("删除交易: tradeId={}, userId={}", tradeId, userId);
        
        // 物理删除：直接从数据库中删除记录
        int result = tradeMapper.delete(tradeId, userId);
        
        if (result == 0) {
            log.warn("删除交易失败，交易不存在或用户无权限: tradeId={}, userId={}", tradeId, userId);
            throw new RuntimeException("删除失败，交易不存在或无权限");
        }
        
        log.info("交易删除成功: tradeId={}", tradeId);
    }
}
